package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edais.dao.CenterDao;
import com.edais.dao.FinancePlanDao;
import com.edais.domain.Finance;
import com.edais.domain.PlanCategorys;
import com.edais.service.FinancePlanService;
import com.edais.util.Arrays;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.vo.FinanceListVo;
import com.edais.vo.FinanceVo;
import com.edais.vo.PlanCategorysVo;

@Service

public class FinancePlanServiceImp implements FinancePlanService {
	private static final Log logger = LogFactory.getLog(FinancePlanServiceImp.class);

	@Autowired
	private FinancePlanDao financeDao;
	
	@Autowired
	private CenterDao centerDao;

	@Override
	public String getFinancesCount(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		return financeDao.getFinancesCount(map);
	}

	@Override
	public List<FinanceListVo> getFinanceList(Map<String, Object> map) throws Exception {
		// TODO Auto-generated method stub
		List<Finance> financeList = financeDao.getFinanceList(map);
		List<FinanceListVo> FinanceListVo = new ArrayList<FinanceListVo>();
		for(Finance finance: financeList){
			FinanceListVo financeVo = new FinanceListVo();
			financeVo.setFinanceID(finance.getId()+"");
			financeVo.setFinanceName(finance.getName());
			financeVo.setExpectedRate(null ==finance.getExpected_rate()?"":finance.getExpected_rate());
			financeVo.setMinInvestMoney(finance.getMin_buyer_amount()+"");
			financeVo.setBaseLockPeriod(finance.getBase_lock_period() + "");
			financeVo.setEnableBuy(finance.getEnable_buy());
			financeVo.setAssurance("本息保证");
			financeVo.setMaxInvestMoney(null == finance.getMax_buyer_amount()?"":finance.getMax_buyer_amount()+"");
			FinanceListVo.add(financeVo);
		}
		return FinanceListVo;
	}

	@Override
	public String getChildFinancePlanCount(String queryFlag) throws Exception {
		return financeDao.getChildFinancePlanCount(queryFlag);
	}

	@Override
	public List<Map<String,Object>> getChildFinancePlanList(String queryFlag) throws Exception {
		List<Finance> financeList = financeDao.getChildFinancePlanList(queryFlag);
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		for(Finance finance: financeList){
			HashMap<String,Object> haspMap = new HashMap<String,Object>();
			haspMap.put("financeID", finance.getId()+"");
			haspMap.put("financeName", finance.getName());
			mapList.add(haspMap);
		}
		return mapList;
	}

	/**
	 * 获取产品一级分类列表
	 */
	@Override
	public List<PlanCategorysVo> getCategorys(Map<String, Object> map) throws Exception {
		List<PlanCategorys> planCategorysList = financeDao.getCategorys(map);
		List<PlanCategorysVo> planCategorysVo = new ArrayList<PlanCategorysVo>();
		for(PlanCategorys planCategorys: planCategorysList){
			PlanCategorysVo planCategoryVo = new PlanCategorysVo();
			planCategoryVo.setFinanceName(planCategorys.getFinance_name());
			planCategoryVo.setCategoryId(planCategorys.getId()+"");
			planCategoryVo.setLogoUrl(null ==planCategorys.getLogo_url()?"":planCategorys.getLogo_url());
			planCategoryVo.setAnnualRateReturn(null ==planCategorys.getAnnual_rate_return()?"":planCategorys.getAnnual_rate_return());
			planCategoryVo.setLabels(null ==planCategorys.getLabels()?"":planCategorys.getLabels());
			planCategoryVo.setLogogramName(null ==planCategorys.getLogogram_name()?"":planCategorys.getLogogram_name());
			planCategoryVo.setFeatures(null ==planCategorys.getFeatures()?"":planCategorys.getFeatures());
			planCategoryVo.setFplan_id(null ==planCategorys.getFplan_id()?"":planCategorys.getFplan_id());
			planCategorysVo.add(planCategoryVo);
		}
		return planCategorysVo;
	}

	/**
	 * 根据一级分类获取所属产品
	 */
	@Override
	public List<FinanceVo> getPlansByKind(Map<String, Object> map) throws Exception {
		List<Finance> planList = financeDao.getPlansByKind(map);
		List<FinanceVo> planVoList = new ArrayList<FinanceVo>();
		for(Finance plan:planList){
			FinanceVo planVo = new FinanceVo();
			
			planVo.setPlanId(plan.getId().toString());
			// 机构
			planVo.setCoagency(null == plan.getLogogram_name()?"":plan.getLogogram_name());
			// 年化收益率
			planVo.setExpectedRate(plan.getExpected_rate());
			// 产品介绍
			planVo.setIntroduce(null == plan.getIntroduce()? "":plan.getIntroduce());
			// 起投金额
			planVo.setMinInvestMoney(String.valueOf(null == plan.getMin_buyer_amount()? "": plan.getMin_buyer_amount()));
			// 名称
			planVo.setName(plan.getName());
			// 提现费率
			planVo.setWithdrawalRate(null == plan.getWithdraw_fee_memo()?"0%":plan.getWithdraw_fee_memo());
			//基础所定期
			planVo.setBaseLockPeriod(plan.getBase_lock_period() + "");
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			//计划开始销售时间
//			planVo.setPlanBeginSellingTime(null == plan.getPlan_begin_selling_time()? "":df.format(plan.getPlan_begin_selling_time()));
//			//计划停止销售时间
//			planVo.setPlanEndSellingTime(null == plan.getPlan_end_selling_time()? "":df.format(plan.getPlan_end_selling_time()));
			//是否允许购买(Y/N)
			planVo.setEnableBuy(plan.getEnable_buy());
			//循环方式类型，以逗号分隔cycleMatchType
			String[] cycleMatchType = centerDao.getCycleMatchType(plan.getId().toString());
			if(null == cycleMatchType ||  cycleMatchType.length <= 0 ){
				planVo.setCycleMatchType(Consts.CycleMatchType.NOCYCLE);
			}else{
				planVo.setCycleMatchType(Arrays.toString(cycleMatchType));
			}
			//退出费用
			planVo.setAssignRatio(null == plan.getExit_fee_memo()?"":plan.getExit_fee_memo());
			//是否设置回款卡号(Y/N)
			Integer reseiptType = plan.getReseipt_type();
			if(null == reseiptType || 3 ==reseiptType){
				planVo.setReseiptType("Y");
			}else{
				planVo.setReseiptType("N");
			}
			//是否支持使用邀请码功能(Y/N)
			planVo.setIsSupInvitationCd(null == plan.getIf_support_invicode()?"N":plan.getIf_support_invicode());
//			//投资金额上限
			planVo.setMaxInvestMoney(null == plan.getMax_buyer_amount()? "":plan.getMax_buyer_amount()+"");
			//特性
			planVo.setFeatures(null == plan.getFeatures()? "":plan.getFeatures()+"");
			
			// 设置报文体报文数据
			Map<String, Object> pageModel = new HashMap<String, Object>();
			// 用户id
			pageModel.put("productId", plan.getId());
			pageModel.put("queryFlag","");
			// 核心接口（E计划显示统计）
			String transCode = "E300007";
			
			try {
				// 构建json字符串
				String jsonStr = CommonUtil.constructJsonStr(transCode, plan.getId()+"", pageModel);
				String rtnStr = CommonUtil.getCoreValue(jsonStr);
				JSONObject jsonObject = (JSONObject) JSON.parse(rtnStr);
				
				// rescode = "00000"
				if(jsonObject != null && Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
					String people = jsonObject.getString("people");//累计参与者
					String money = jsonObject.getBigDecimal("money").setScale(2, BigDecimal.ROUND_DOWN).toString();//累计投入金额
					planVo.setHeadCount(people == null || "".equals(people) ? "0" : people);
					planVo.setTotalLimit(money == null || "".equals(money) ? "0.00" : money);
					
					BigDecimal headCount = new BigDecimal(planVo.getHeadCount());
					BigDecimal totalLimit = new BigDecimal(planVo.getTotalLimit());
					
					BigDecimal perCapitaAmount = BigDecimal.ZERO;//人均购买金额
					if(!"0".equals(planVo.getHeadCount())){
						perCapitaAmount = totalLimit.divide(headCount,2);
					}
					planVo.setPerCapitaAmount(perCapitaAmount.toString());
					
				} else {
					logger.debug("=====核心接口调用异常=====");
					logger.debug("iface：E300007  rescode：" + jsonObject.getString("rescode") + "  resmsg：" + jsonObject.getString("resmsg"));
					planVo.setHeadCount("0");
					planVo.setTotalLimit("0.00");
					planVo.setPerCapitaAmount("0.00");
				}	
			} catch (Exception ex) {
				logger.debug("=====核心接口调用异常=====");
				planVo.setHeadCount("0");
				planVo.setTotalLimit("0.00");
				planVo.setPerCapitaAmount("0.00");
			}
			planVoList.add(planVo);
		}
		return planVoList;
	}

	@Override
	public Map<String, Object> getCategoryList(Map<String, Object> map) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<PlanCategorysVo> list = new ArrayList<PlanCategorysVo>();
		// 获取总记录数
		String totalNum = financeDao.getCategoryNum(map);
		// 获取记录
		if (Integer.valueOf(totalNum) > 0) {
			list = getCategorys(map);
		}
		rtnMap.put("totalNum", totalNum);
		rtnMap.put("listSize", list.size());
		rtnMap.put("planCategoryList", list);
		return rtnMap;
	}

	@Override
	public Map<String, Object> getPlanListByKind(Map<String, Object> map) throws Exception {
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		List<FinanceVo> planList = new ArrayList<FinanceVo>();
		// 获取总记录数
		String totalNum = financeDao.getPlanNum(map);
		// 获取记录
		if (Integer.valueOf(totalNum) > 0) {
			planList = getPlansByKind(map);
		}
		rtnMap.put("totalNum", totalNum);
		rtnMap.put("listSize", planList.size());
		rtnMap.put("planList", planList);
		return rtnMap;
	}
}
